<!--
 @description 装修实景-分页列表
 @fileName List.vue
 @author zengqiongying
 @created 2023-09-11 14:28:33
-->
<template>
  <List ref="list" :set-page-size="10" :finished.sync="finished" :reset-fun="resetData" :load="load" :refresh="load">
    <div class="reality-container">
      <div
        v-for="(item,i) in list"
        :key="i"
        :class="['waterfall-item']"
        :style="{
          'grid-row':item.gridRow
        }"
      >
        <div :class="['con-wrap','water-wrap-'+i]" @click="clickHandle(item)">
          <div class="image">
            <ImageVideo lazy-load :host="host" :src="item.realityPic" fit="fill" @load="calcImageHeight(i)" />
            <div v-if="[1,'1'].includes(item.contributeType)" class="icon-play">
              <img src="~@/assets/icon_player.png">
            </div>
          </div>
          <div class="name">{{ item.realityName }}</div>
        </div>
      </div>
    </div>

  </List>
</template>

<script>
import List from '@/components/PageList'
import ImageVideo from '@/components/ImageVideo'
import { randomId } from '@/utils'
import { mapGetters, mapMutations, mapActions } from 'vuex'
import { getRealitySceneFilter, getAttrList, getRealityPage, getSeriesByStyleId, getCategoryByOneSpace } from '@/apis/realityScene'

export default {
  name: 'RealitySceneSchemeList',
  components: { List, ImageVideo },
  refresh: true,
  props: {
    contributeType: {
      type: [String, Number],
      default: 1
    }
  },
  data() {
    return {
      host: `${process.env.VUE_APP_ADS_STATIC}`,
      list: [],
      finished: false,
      spaceStyleFilter: [], // 空间风格筛选条件
      sort: 'createTime',
      spaceCode: '', // 空间编码
      styleCode: '', // 风格编码
      seriesCode: '', // 系列编码
      categoryCode: '', // 品类编码
      leftList: [],
      rightList: []
    }
  },
  computed: {
    ...mapGetters('nav', ['filterData'])
  },
  watch: {
    contributeType(val, oldVal) {
      this.resetFilterData()
      this.resetPageData()
    }
  },
  created() {
    this.getAttrFilter()
    this.$on('refresh', this.resetPageData)
  },
  activated() {
    // 读取缓存中的筛选条件
    const filterStr = sessionStorage.getItem('realityFilterData')
    let data = []
    if (filterStr) {
      try {
        data = JSON.parse(filterStr)
      } catch {
        console.log('存储的筛选条件格式异常')
      }
      sessionStorage.removeItem('realityFilterData')
    }
    this.updateFilterData(data)
  },
  methods: {
    ...mapActions('nav', ['getFilterData']),
    ...mapMutations('nav', ['updateFilterData', 'updateRsetSelectList']),

    resetPageData(v) {
      if (v === 'confirm') return
      if (this.$refs.list) {
        this.$refs.list.resetPageData()
      }
    },
    resetData() {
      this.list = []
      this.leftList = []
      this.rightList = []
    },
    async load(page, rows) {
      const selectedData = this.$extrFilterData(this.filterData)
      // 风格
      const styleCode = this.$extrFIlterValueByFlag(selectedData, 'adsStyleDTOS')
      // 空间
      const spaceCode = this.$extrFIlterIdxByFlag(selectedData, 'adsSpaceDTOS')
      // 系列
      const seriesCode = this.styleCode === styleCode ? this.$extrFIlterIdxByFlag(selectedData, 'adsSeriesDTOS') : ''
      // 品类
      const categoryCode = this.spaceCode === spaceCode ? this.$extrFIlterIdxByFlag(selectedData, 'adsCategoryDTOS') : ''

      // /排序
      const sort = this.$extrFIlterValueByFlag(selectedData, /^sort*/, false).join(',')
      const filtersRaw = [
        { id: 'approveState', property: 'approveState', value: '1', operator: '=' },
        { id: 'upState', property: 'upState', value: '0', operator: '=' },
        { id: 'tagCode', property: 'tagCode', value: this.contributeType === 1 ? 'SAMPLE_ROOM_VIDEO' : 'SAMPLE_ROOM_PICTURE', operator: '=' }
      ]
      let sortersRaw = []
      if (['browseNum'].includes(sort)) {
        this.sort = sort
        sortersRaw.push({
          id: sort, property: sort, direction: 'DESC'
        })
      } else {
        this.sort = 'createTime'
        sortersRaw = [
          { id: 'topTime', property: 'topTime', direction: 'DESC' },
          { id: 'createTime', property: 'createTime', direction: 'DESC' }
        ]
      }
      if (spaceCode) {
        filtersRaw.push({ id: 'spaceCode', property: 'spaceCode', operator: '=', value: spaceCode })
      }
      if (styleCode) {
        filtersRaw.push({ id: 'styleCode', property: 'styleCode', operator: '=', value: styleCode })
      }
      if (categoryCode) {
        this.categoryCode = categoryCode
        filtersRaw.push({ id: 'categoryCode', property: 'categoryCode', operator: '=', value: categoryCode })
      }
      if (seriesCode) {
        this.seriesCode = seriesCode
        filtersRaw.push({ id: 'seriesCode', property: 'seriesCode', operator: '=', value: seriesCode })
      }
      const params = {
        page,
        rows,
        filtersRaw: JSON.stringify(filtersRaw),
        pageFlag: true,
        sortersRaw: JSON.stringify(sortersRaw)
      }
      this.refreshFilterData({ spaceCode, styleCode })

      return getRealityPage(params).then(res => {
        const data = res.data || ''
        if (data) {
          if (data.records) {
            const list = data.records || []
            this.list.push(...list)
            const leftList = []
            const rightList = []
            list.forEach((v, i) => {
              if (i % 2 === 0) {
                leftList.push(v)
              } else {
                rightList.push(v)
              }
            })
            this.leftList.push(...leftList)
            this.rightList.push(...rightList)
          }
        }

        if (!data || !(data.records && data.records.length) || (data.totalRows <= this.list.length)) {
          this.finished = true
        }
      })
    },
    // 联动刷新系列和品类筛选条件
    async refreshFilterData({ spaceCode, styleCode }) {
      let filterData = this.filterData.filter(v => v.flag !== 'sort')
      const styleIndex = filterData.findIndex(v => v.flag === 'adsStyleDTOS')
      const spaceIndex = filterData.findIndex(v => v.flag === 'adsSpaceDTOS')
      if (styleCode && this.styleCode !== styleCode) {
        // 更新系列筛选条件
        let list = []
        await getSeriesByStyleId(styleCode).then(res => {
          list = res.data || []
        }).catch(() => {})
        if (list.length > 0 && styleIndex > -1) {
          // 系列条件添加到风格后面
          const i = filterData.findIndex(v => v.flag === 'adsSeriesDTOS')
          if (i === -1) {
            filterData.splice(styleIndex + 1, 0, list[0])
          } else {
            filterData[i] = list[0]
          }
        } else {
          filterData = filterData.filter(v => v.flag !== 'adsSeriesDTOS')
        }
      }
      if (spaceCode && this.spaceCode !== spaceCode) {
        // 更新品类筛选条件
        let list = []
        await getCategoryByOneSpace(spaceCode).then(res => {
          list = res.data || []
        }).catch(() => {})
        if (list.length > 0 && spaceIndex > -1) {
          // 品类条件添加到空间后面
          const i = filterData.findIndex(v => v.flag === 'adsCategoryDTOS')
          if (i === -1) {
            filterData.splice(spaceIndex + 1, 0, list[0])
          } else {
            filterData[i] = list[0]
          }
        } else {
          filterData = filterData.filter(v => v.flag !== 'adsCategoryDTOS')
        }
      }
      this.styleCode = styleCode || ''
      this.spaceCode = spaceCode || ''
      const sortRaw = this.getSortFilter()
      const newFilterData = [...sortRaw, ...filterData]
      this.updateFilterData(newFilterData)
    },
    getSortFilter() {
      const sortRaw = [
        {
          unId: randomId(),
          title: '排序',
          show: true,
          flag: 'sort',
          type: 'sort',
          multiple: false,
          isMultChoose: false,
          children: [
            { label: '默认', value: 'createTime', selected: !['browseNum'].includes(this.sort) },
            { label: '最热', value: 'browseNum', selected: this.sort === 'browseNum' }
          ]
        }
      ]
      return sortRaw
    },
    // 获取风格、空间数据，初始化筛选数据
    async getAttrFilter() {
      const sortRaw = this.getSortFilter()
      getAttrList().then(res => {
        const filterData = res.data || []
        this.spaceStyleFilter = filterData
        if (this.contributeType !== 1) {
          this.updateFilterData([...sortRaw, ...filterData])
        } else {
        // 视频筛选条件不要空间品类
          const filterVideo = filterData.filter(v => v.flag !== 'adsSpaceDTOS')
          this.updateFilterData([...sortRaw, ...filterVideo])
        }
      })
    },
    resetFilterData() {
      this.spaceCode = ''
      this.styleCode = ''
      this.sort = 'createTime'
      const sortRaw = this.getSortFilter()
      if (this.contributeType !== 1) {
        this.updateFilterData([...sortRaw, ...this.spaceStyleFilter])
      } else {
        // 视频筛选条件不要空间品类
        const filterVideo = this.spaceStyleFilter.filter(v => v.flag !== 'adsSpaceDTOS')
        this.updateFilterData([...sortRaw, ...filterVideo])
      }
      this.updateRsetSelectList([])
    },
    clickHandle(item) {
      // 存储查询条件
      sessionStorage.setItem('realityFilterData', JSON.stringify(this.filterData))
      this.$nextTick(() => {
        const { id } = item
        this.$router.push({
          name: [1, '1'].includes(item.contributeType) ? 'RealityVideoDetail' : 'RealityPicDetail',
          params: {
            id
          }
        })
      })
    },
    calcImageHeight(i) {
      const container = document.querySelector('.water-wrap-' + i)
      const height = getComputedStyle(container).getPropertyValue('height')
      const num = Math.round(height.replace('px', ''))
      this.$set(this.list[i], 'gridRow', 'auto/span ' + num)
      console.log(num)
    }
  }
}

</script>
<style lang='less' scoped>
.reality-page-list{
  display: flex;
  padding-top: 8px;
  .list-left{
    width: 50%;
    padding: 0 4px 0 7px;
    box-sizing: border-box;
  }
  .list-right{
    width: 50%;
    padding: 0 7px 0 4px;
    box-sizing: border-box;
  }

}
.reality-container{
  display: grid;
  grid-template-columns:169px auto;
  column-gap:8px;
  box-sizing: border-box;
  margin: 0 auto;
  padding: 8px 14px 0;
  width: 100%;
  box-sizing: border-box;
  .waterfall-item {
    box-sizing: border-box;
    margin-bottom:10px;
    width: 100%;
    height: 100%;
    transition: all 0.3s;
    cursor: pointer;
    .con-wrap{
        width: 100%;
        background: #fff;
        border-radius: 8px 8px 0 0;
        overflow: hidden;
        .image{
          position: relative;
          width: 100%;
          // height: 210px;
          border-radius: 8px 8px 0 0;
          overflow: hidden;
          .icon-play{
            position: absolute;
            left: 14px;
            top: 14px;
            z-index: 9;
            width: 18px;
            height: 18px;
            img{
              width: 18px;
              height: 18px;
            }
          }
        }
        .name{
          padding: 12px 8px;
          font-size: 14px;
          font-weight: 500;
          color: #3C4458;
          line-height: 20px;
        }
      }
  }
}

</style>
